import { app, BrowserWindow, globalShortcut, ipcMain, screen, desktopCapturer, nativeImage, dialog, Menu } from 'electron'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { promises as fs } from 'fs'
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs'
import { createTray } from './tray'

// 解决 ESM 模块中 __dirname 未定义的问题
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 禁用硬件加速以避免某些显卡驱动问题
app.disableHardwareAcceleration()

let mainWindow: BrowserWindow | null = null
let screenshotWindow: BrowserWindow | null = null

// 快捷键配置
interface ShortcutConfig {
  screenshot: string
}

const DEFAULT_SHORTCUTS: ShortcutConfig = {
  screenshot: 'CommandOrControl+Alt+A'
}

let currentShortcuts: ShortcutConfig = { ...DEFAULT_SHORTCUTS }

// 快捷键存储路径
const getShortcutsPath = () => {
  const userDataPath = app.getPath('userData')
  return join(userDataPath, 'shortcuts.json')
}

// 读取快捷键配置
function loadShortcuts(): ShortcutConfig {
  try {
    const path = getShortcutsPath()
    if (existsSync(path)) {
      const data = readFileSync(path, 'utf-8')
      const config = JSON.parse(data)
      console.log('加载快捷键配置:', config)
      return config
    }
  } catch (error) {
    console.error('读取快捷键配置失败:', error)
  }
  return { ...DEFAULT_SHORTCUTS }
}

// 保存快捷键配置
function saveShortcuts(config: ShortcutConfig): void {
  try {
    const path = getShortcutsPath()
    writeFileSync(path, JSON.stringify(config, null, 2), 'utf-8')
    console.log('保存快捷键配置成功:', config)
  } catch (error) {
    console.error('保存快捷键配置失败:', error)
  }
}

// 创建菜单栏
function createMenu() {
  const template: any = [
    {
      label: '文件',
      submenu: [
        {
          label: '新建截图',
          accelerator: 'Ctrl+Alt+A',
          click: () => {
            handleScreenshot()
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: 'Ctrl+Q',
          click: () => {
            app.quit()
          }
        }
      ]
    },
    {
      label: '工具',
      submenu: [
        {
          label: 'OCR 状态',
          click: () => {
            if (mainWindow) {
              mainWindow.webContents.send('show-ocr-status')
            }
          }
        },
        {
          label: '初始化 OCR',
          click: () => {
            if (mainWindow) {
              mainWindow.webContents.send('init-ocr')
            }
          }
        },
        { type: 'separator' },
        {
          label: '🔄 重启应用',
          accelerator: 'Ctrl+Shift+R',
          click: () => {
            console.log('准备重启应用...')
            
            // 开发环境：只刷新主窗口
            if (process.env.VITE_DEV_SERVER_URL) {
              console.log('开发环境：刷新主窗口')
              
              // 关闭截图窗口
              if (screenshotWindow && !screenshotWindow.isDestroyed()) {
                screenshotWindow.close()
                screenshotWindow = null
              }
              
              // 刷新主窗口
              if (mainWindow && !mainWindow.isDestroyed()) {
                mainWindow.reload()
              }
              return
            }
            
            // 生产环境：完整重启流程
            console.log('生产环境：完整重启')
            
            // 1. 关闭截图窗口
            if (screenshotWindow && !screenshotWindow.isDestroyed()) {
              console.log('关闭截图窗口')
              screenshotWindow.close()
              screenshotWindow = null
            }
            
            // 2. 关闭主窗口
            if (mainWindow && !mainWindow.isDestroyed()) {
              console.log('关闭主窗口')
              mainWindow.close()
              mainWindow = null
            }
            
            // 3. 注销全局快捷键
            console.log('注销快捷键')
            globalShortcut.unregisterAll()
            
            // 4. 延迟重启（确保清理完成）
            setTimeout(() => {
              console.log('执行重启')
              app.relaunch()
              app.quit()
            }, 300)
          }
        },
        { type: 'separator' },
        {
          label: '打开开发者工具',
          accelerator: 'F12',
          click: () => {
            mainWindow?.webContents.openDevTools()
          }
        }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            dialog.showMessageBox({
              type: 'info',
              title: '关于截图工具',
              message: '截图工具 v1.0.0',
              detail: '功能强大的截图标注工具，支持 OCR 文字识别\n\n技术栈：Electron + Vue 3 + TypeScript',
              buttons: ['确定']
            })
          }
        }
      ]
    }
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

// 创建主窗口
function createWindow() {
  // 设置应用图标路径
  const iconPath = app.isPackaged
    ? join(process.resourcesPath, 'public', 'icon.png')
    : join(__dirname, '..', 'public', 'icon.png')
  
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    icon: iconPath,
    webPreferences: {
      preload: join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
      webSecurity: false
    },
    show: false
  })

  // 创建菜单栏
  createMenu()

  // 开发环境加载本地服务，生产环境加载构建后的文件
  if (process.env.VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
    // mainWindow.webContents.openDevTools() // 默认不打开开发者工具，需要时按 F12
  } else {
    mainWindow.loadFile(join(__dirname, '../dist/index.html'))
  }

  mainWindow.once('ready-to-show', () => {
    mainWindow?.show()
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

// 创建截图窗口
async function createScreenshotWindow() {
  // 获取主显示器信息
  const primaryDisplay = screen.getPrimaryDisplay()
  const { width, height } = primaryDisplay.bounds

  screenshotWindow = new BrowserWindow({
    fullscreen: true,
    width,
    height,
    transparent: true,
    frame: false,
    skipTaskbar: true,
    alwaysOnTop: true,
    resizable: false,
    movable: false,
    webPreferences: {
      preload: join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true
    },
    show: false
  })

  // 加载截图页面
  if (process.env.VITE_DEV_SERVER_URL) {
    await screenshotWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}#/screenshot`)
  } else {
    await screenshotWindow.loadFile(join(__dirname, '../dist/index.html'), { hash: 'screenshot' })
  }

  // // 等待页面完全加载，确保 preload 已执行（暂时注释）
  // await new Promise<void>(resolve => {
  //   screenshotWindow!.webContents.on('did-finish-load', () => {
  //     console.log('[主进程] 截图窗口加载完成')
  //     resolve()
  //   })
  // })

  screenshotWindow.once('ready-to-show', () => {
    screenshotWindow?.show()
    screenshotWindow?.focus()
    screenshotWindow?.setFullScreen(true)
  })

  screenshotWindow.on('closed', () => {
    screenshotWindow = null
  })

  // // 开发环境：防止热重载导致的问题（暂时注释）
  // if (process.env.VITE_DEV_SERVER_URL) {
  //   screenshotWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
  //     console.error('[主进程] 截图窗口加载失败:', errorCode, errorDescription)
  //   })
  // }
}

// 注册全局快捷键
function registerShortcuts() {
  // 先注销所有快捷键
  globalShortcut.unregisterAll()
  
  // 注册截图快捷键
  const shortcut = currentShortcuts.screenshot
  const ret = globalShortcut.register(shortcut, () => {
    handleScreenshot()
  })

  if (!ret) {
    console.log(`快捷键 ${shortcut} 注册失败，可能已被其他程序占用`)
    dialog.showMessageBox({
      type: 'warning',
      title: '快捷键冲突',
      message: `快捷键 ${shortcut} 已被其他程序占用`,
      detail: '请在设置中更改快捷键',
      buttons: ['确定']
    })
  } else {
    console.log(`快捷键 ${shortcut} 注册成功`)
  }
}

// 检查快捷键是否可用（用于冲突检测）
function checkShortcutAvailable(shortcut: string): boolean {
  // 尝试注册一个临时快捷键
  const ret = globalShortcut.register(shortcut, () => {})
  if (ret) {
    // 注册成功，立即注销
    globalShortcut.unregister(shortcut)
    return true
  }
  return false
}

// 更新快捷键
function updateShortcut(name: string, shortcut: string): boolean {
  try {
    // 先注销旧的
    globalShortcut.unregisterAll()
    
    // 注册新的
    const ret = globalShortcut.register(shortcut, () => {
      if (name === 'screenshot') {
        handleScreenshot()
      }
    })
    
    if (ret) {
      // 更新配置
      currentShortcuts[name as keyof ShortcutConfig] = shortcut
      saveShortcuts(currentShortcuts)
      console.log(`快捷键已更新: ${name} -> ${shortcut}`)
      return true
    } else {
      // 注册失败，恢复旧的快捷键
      registerShortcuts()
      return false
    }
  } catch (error) {
    console.error('更新快捷键失败:', error)
    // 恢复旧的快捷键
    registerShortcuts()
    return false
  }
}

// 处理截图请求
async function handleScreenshot() {
  try {
    // 隐藏主窗口
    if (mainWindow && mainWindow.isVisible()) {
      mainWindow.hide()
    }

    // 等待一小段时间让窗口完全隐藏
    await new Promise(resolve => setTimeout(resolve, 100))

    // 捕获屏幕
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: screen.getPrimaryDisplay().bounds
    })

    if (sources.length > 0) {
      // 创建或显示截图窗口
      if (!screenshotWindow || screenshotWindow.isDestroyed()) {
        console.log('[主进程] 创建新的截图窗口')
        await createScreenshotWindow()
        // 新创建的窗口需要更多时间初始化
        await new Promise(resolve => setTimeout(resolve, 300))
      } else {
        console.log('[主进程] 复用现有截图窗口')
        screenshotWindow.show()
        screenshotWindow.focus()
        screenshotWindow.setFullScreen(true)
        // 复用窗口只需短暂等待
        await new Promise(resolve => setTimeout(resolve, 50))
      }

      // 发送截图数据到渲染进程
      const screenData = sources.map(source => ({
        id: source.id,
        name: source.name,
        thumbnail: source.thumbnail.toDataURL()
      }))

      console.log('[主进程] 发送截图数据到渲染进程')
      screenshotWindow?.webContents.send('screenshot-sources', screenData)
    }
  } catch (error) {
    console.error('截图失败:', error)
    // 失败时重新显示主窗口
    if (mainWindow) {
      mainWindow.show()
    }
  }
}

// IPC 通信处理
ipcMain.handle('take-screenshot', async () => {
  await handleScreenshot()
})

ipcMain.handle('close-screenshot', () => {
  console.log('[主进程] 收到关闭截图请求')
  if (screenshotWindow && !screenshotWindow.isDestroyed()) {
    screenshotWindow.hide()
    console.log('[主进程] 截图窗口已隐藏（窗口保留，可复用）')
  }
  // 重新显示主窗口
  if (mainWindow) {
    mainWindow.show()
    console.log('[主进程] 主窗口已显示')
  }
})

ipcMain.handle('get-screen-sources', async () => {
  try {
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: screen.getPrimaryDisplay().bounds
    })

    return sources.map(source => ({
      id: source.id,
      name: source.name,
      thumbnail: source.thumbnail.toDataURL()
    }))
  } catch (error) {
    console.error('获取屏幕源失败:', error)
    return []
  }
})

// 保存截图到文件
ipcMain.handle('save-screenshot', async (event, dataUrl: string, filename: string) => {
  try {
    // 获取图片文件夹路径
    const picturesPath = app.getPath('pictures')
    const screenshotsDir = join(picturesPath, 'Screenshots')
    
    // 确保 Screenshots 目录存在
    if (!existsSync(screenshotsDir)) {
      mkdirSync(screenshotsDir, { recursive: true })
    }
    
    console.log('默认保存路径:', screenshotsDir)
    console.log('文件名:', filename)
    
    const { filePath, canceled } = await dialog.showSaveDialog({
      title: '保存截图',
      defaultPath: join(screenshotsDir, filename),
      filters: [
        { name: 'PNG 图片', extensions: ['png'] },
        { name: 'JPEG 图片', extensions: ['jpg', 'jpeg'] },
        { name: '所有文件', extensions: ['*'] }
      ],
      properties: ['showOverwriteConfirmation']
    })

    console.log('用户选择的路径:', filePath)
    console.log('是否取消:', canceled)

    if (canceled || !filePath) {
      return { success: false, canceled: true }
    }

    // 提取 base64 数据
    const base64Data = dataUrl.replace(/^data:image\/\w+;base64,/, '')
    const buffer = Buffer.from(base64Data, 'base64')
    
    console.log('图片大小:', buffer.length, 'bytes')
    
    // 确保目标目录存在
    const dir = dirname(filePath)
    if (!existsSync(dir)) {
      console.log('创建目录:', dir)
      mkdirSync(dir, { recursive: true })
    }
    
    // 写入文件
    writeFileSync(filePath, buffer)
    console.log('文件保存成功:', filePath)
    
    return { success: true, path: filePath }
  } catch (error) {
    console.error('保存截图失败:', error)
    return { success: false, error: String(error) }
  }
})

// 自动保存截图（不弹窗）
ipcMain.handle('auto-save-screenshot', async (event, dataUrl: string, filename: string) => {
  try {
    const screenshotsDir = join(app.getPath('pictures'), 'Screenshots')
    
    // 确保目录存在
    if (!existsSync(screenshotsDir)) {
      mkdirSync(screenshotsDir, { recursive: true })
    }
    
    const filePath = join(screenshotsDir, filename)
    const base64Data = dataUrl.replace(/^data:image\/\w+;base64,/, '')
    const buffer = Buffer.from(base64Data, 'base64')
    
    writeFileSync(filePath, buffer)
    return { success: true, path: filePath }
  } catch (error) {
    console.error('自动保存截图失败:', error)
    return { success: false, error: String(error) }
  }
})

// 复制到剪贴板
ipcMain.handle('copy-to-clipboard', async (event, dataUrl: string) => {
  try {
    const { clipboard } = await import('electron')
    const img = nativeImage.createFromDataURL(dataUrl)
    clipboard.writeImage(img)
    return { success: true }
  } catch (error) {
    console.error('复制到剪贴板失败:', error)
    return { success: false, error: String(error) }
  }
})

// 快捷键冲突检测
ipcMain.handle('check-shortcut-conflict', async (event, shortcut: string) => {
  try {
    const available = checkShortcutAvailable(shortcut)
    return { available }
  } catch (error) {
    console.error('检查快捷键冲突失败:', error)
    return { available: false, error: String(error) }
  }
})

// 更新快捷键
ipcMain.handle('update-shortcut', async (event, name: string, shortcut: string) => {
  try {
    const success = updateShortcut(name, shortcut)
    if (success) {
      return { success: true }
    } else {
      return { success: false, error: '快捷键已被占用' }
    }
  } catch (error) {
    console.error('更新快捷键失败:', error)
    return { success: false, error: String(error) }
  }
})

// 显示主窗口
function showMainWindow() {
  if (mainWindow) {
    if (mainWindow.isMinimized()) {
      mainWindow.restore()
    }
    mainWindow.show()
    mainWindow.focus()
  } else {
    createWindow()
  }
}

// 应用程序准备就绪
app.whenReady().then(() => {
  // 加载快捷键配置
  currentShortcuts = loadShortcuts()
  console.log('当前快捷键配置:', currentShortcuts)
  
  createWindow()
  
  // 创建托盘（添加错误处理）
  try {
    console.log('开始创建系统托盘...')
    // 设置托盘图标路径
    const trayIconPath = app.isPackaged
      ? join(process.resourcesPath, 'public', 'icon.png')
      : join(__dirname, '..', 'public', 'icon.png')
    console.log('托盘图标路径（main.ts）:', trayIconPath)
    createTray(handleScreenshot, trayIconPath, showMainWindow)
    console.log('系统托盘创建成功')
  } catch (error) {
    console.error('创建系统托盘失败:', error)
  }
  
  // 注册快捷键（使用加载的配置）
  registerShortcuts()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

// 所有窗口关闭时
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 应用退出前注销快捷键
app.on('will-quit', () => {
  globalShortcut.unregisterAll()
})




